package secondriver.springsubway.example.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import secondriver.springsubway.example.bean.User;
import secondriver.springsubway.example.dao.RedisDaoHelper;

public class UserManagerController extends MultiActionController {

	private RedisDaoHelper redisDaoHelper;

	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "register";
	}

	public ModelAndView register(HttpServletRequest request,
			HttpServletResponse response) {
		if (!request.getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
			return new ModelAndView("register");
		}
		User user = wrapperUserFromRequest(request);
		ModelAndView modelAndView = new ModelAndView();

		if (redisDaoHelper.userRegister(user)) {
			modelAndView.setViewName("success");
			modelAndView.addObject("user", user);
			modelAndView.addObject("message", "注册成功");

		} else {
			modelAndView.setViewName("register");
			modelAndView.addObject("message", "用户名已经存在");
		}
		return modelAndView;
	}

	public ModelAndView login(HttpServletRequest request,
			HttpServletResponse response) {
		if (!request.getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
			return new ModelAndView("register");
		}
		User user = wrapperUserFromRequest(request);
		ModelAndView modelAndView = new ModelAndView();
		if (redisDaoHelper.userLogin(user)) {
			modelAndView.setViewName("success");
			modelAndView.addObject("user", user);
			modelAndView.addObject("message", "登录成功");
		} else {
			modelAndView.setViewName("register");
			modelAndView.addObject("message", "登录失败");
		}
		return modelAndView;
	}

	private User wrapperUserFromRequest(HttpServletRequest request) {
		String userName = request.getParameter("user.userName");
		String userPasswd = request.getParameter("user.userPasswd");
		User user = new User();
		user.setUserName(userName);
		user.setUserPasswd(userPasswd);
		return user;
	}

	public RedisDaoHelper getRedisDaoHelper() {
		return redisDaoHelper;
	}

	public void setRedisDaoHelper(RedisDaoHelper redisDaoHelper) {
		this.redisDaoHelper = redisDaoHelper;
	}
}
